package socket.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @description: 类描述
 * @author: Fesine
 * @createTime:2016/9/29 16:38
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2016/9/29 16:38
 */
public class ClientWorker implements Runnable {

    @Override
    public void run() {
        Socket socket = null;
        BufferedReader reader = null;
        PrintWriter writer = null;
        try {
            //创建socket并连接到指定的服务器
            socket = new Socket("localhost", 8383);
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            writer = new PrintWriter(socket.getOutputStream());
            writer.println("who");
            writer.println("what");
            writer.println("where");
            writer.println("over");//over作为结束命令
            writer.flush();
            String answer = reader.readLine();//没有内容会阻塞
            while (!answer.equals("over")) {
                System.out.println(Thread.currentThread().getId() + "---->Message from server:" +
                        answer);
                answer = reader.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
                if (reader != null) {
                    reader.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
